<?php
namespace chat;

use GatewayWorker\Lib\Gateway;
use yii\web\Request;
use yii\helpers\ArrayHelper;
use yii\web\Application;

class Events
{
    /**
     * 消息处理.
     * @param string $client_id 地址ID
     * @param string $msg 数据
     * @return mixed
     */
    static public function onMessage($client_id,$msg)
    {
        // 这里是一个简单的判断.
        $config =ArrayHelper::merge(
            require ROOT_PATH . '/common/config/main.php',
            require ROOT_PATH . '/common/config/main-local.php',
            require ROOT_PATH . '/chat/config/main.php',
            require ROOT_PATH . '/chat/config/main-local.php'
        );

        // 格式,{"url":"/login","type":"POST","data":""}
        $msg = @json_decode($msg,true);

        if(!$msg)
        {
            Gateway::closeClient($client_id);
        }

        if($msg['type'] == 'pong')
        {
            Gateway::sendToClient($client_id,json_encode([
                'type'=>'ping',
            ]));
            return '';
        }

        self::beforeRequest($msg);

        $application = new Application($config);
        $request = self::initRequest($application->getRequest(),$msg);

        // 这里进行修改,然后去得到东西.
        // 设置基本路径
        $response = $application->handleRequest($request);

        $data = $response->data;

        // 这里要进行判断,如果是false
        if(!$data){
            // 关闭链接
            Gateway::closeClient($client_id);
        }
        // 将消息发送回去.
        Gateway::sendToClient($client_id,$data);
        return;
    }

    static private function beforeRequest($data)
    {
        $_SERVER['SCRIPT_FILENAME'] = __DIR__ . '/Events.php';
        $_SERVER['DOCUMENT_ROOT'] = __DIR__;
        $_SERVER['SCRIPT_NAME'] = '/Events.php';
        $_SERVER['PHP_SELF'] = '/Events.php';
        $_SERVER['DOCUMENT_URI'] = '/Events.php';
        $_SERVER['REQUEST_METHOD'] = strtoupper($data['type']);
        $_SERVER['REQUEST_URI'] = empty($data['url']) ? '/' : $data['url'];
        $_SERVER['REQUEST_SCHEME'] = 'http';
        $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
        $_SERVER['PATH_INFO'] = '';
    }

    static private function initRequest(Request $request,$data = [])
    {
        $request->setQueryParams($data['data']);
        $request->setUrl($data['url']);
        return $request;
    }
}